package com.jeesite.modules.wxrobot.web;

import com.jeesite.common.codec.DesUtils;
import com.jeesite.common.codec.EncodeUtils;
import com.jeesite.common.codec.Md5Utils;
import com.jeesite.common.codec.Sha1Utils;
import com.jeesite.common.config.Global;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.sys.dao.UserDao;
import com.jeesite.modules.sys.entity.Role;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.entity.UserRole;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.modules.util.GenerateSequenceUtil;
import com.jeesite.modules.util.HttpGetUtil;
import com.jeesite.modules.wxrobot.entity.JsSysEmployee;
import com.jeesite.modules.wxrobot.entity.JsSysUser;
import com.jeesite.modules.wxrobot.service.JsSysEmployeeService;
import com.jeesite.modules.wxrobot.service.JsSysUserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Dispatch;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信登陆
 */
@Controller
@RequestMapping(value = "${frontPath}/wxrobot")
public class WxLoginController extends BaseController {
    private final String APPID = "wxc408356e52d2bf02";
    private final String SECRET = "4bfe72543e5b8ca1618ca4d2435969cc";

    @Autowired
    private JsSysUserService jsSysUserService;


    /**
     * 得到微信公众号返回的code
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "wx_code")
    public void getWxCode(HttpServletRequest request, HttpServletResponse response, String businessType)
            throws IOException {
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        //授权回调地址

        String redirect_uri="https://wx.hnmaizhelun.com/f/wxrobot/wx_login";

        //简单获取openid的话参数response_type与scope与state参数固定写死即可
        StringBuffer url=new StringBuffer("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +APPID+
                "&redirect_uri="+redirect_uri+"&response_type=code&scope=snsapi_base&state=1#wechat_redirect");
        response.sendRedirect(url.toString());//这里请不要使用get请求单纯的将页面跳转到该url即可
    }

    /**
     * 用户信息
     */
    @RequestMapping(value = {"wx_login", ""})
    public ModelAndView wx_login(String code, Model model){
        String openId = getOpenId(code);
        //String openId = "ee999999999445445555";
        Map<String,String> resultMap = new HashMap<String,String>();
        if(StringUtils.isNotBlank(openId)){
            JsSysUser user = jsSysUserService.getUserByOpenId(openId);
            if(null == user){
                user = new JsSysUser();
                String userCode = GenerateSequenceUtil.generateShortSequenceNo();
                user.setUserCode(userCode);
                user.setTotalScore(0);
                user.setLoginCode(userCode);
                user.setUserName(userCode);
                user.setPassword(encryptPassword("43420024"));
                user.setUserType("employee");
                user.setRefCode(userCode);
                user.setMgrType(0);
                user.setStatus(0);
                user.setCreateBy("system");

                Date current_date = new Date();
                user.setCreateDate(current_date);
                user.setUpdateBy("system");
                user.setUpdateDate(current_date);
                user.setWxOpenid(openId);

                JsSysEmployee jsSysEmployee = new JsSysEmployee();
                jsSysEmployee.setEmpCode(userCode);
                jsSysEmployee.setEmpName(userCode);
                jsSysEmployee.setOfficeCode("SDJN01");
                jsSysEmployee.setOfficeName("企管部");
                jsSysEmployee.setStatus("0");
                jsSysEmployee.setCreateBy("system");
                jsSysEmployee.setCreateDate(current_date);
                jsSysEmployee.setUpdateBy("system");
                jsSysEmployee.setUpdateDate(current_date);
                int re = jsSysUserService.insertUser(user,jsSysEmployee);

                ModelAndView modelAndView = new ModelAndView();
                modelAndView.addObject("usercode",userCode);
                modelAndView.setViewName("modules/wxrobot/unlogin");

                return modelAndView;
            }else{
                User queryUser = UserUtils.get(user.getUserCode());
                List<Role> roleList =  queryUser.getRoleList();
                if(CollectionUtils.isNotEmpty(roleList)){
                    //String secretKey = Global.getConfig("shiro.sso.secretKey");
                    String secretKey = "magellan";
                    String token = Md5Utils.md5(secretKey + queryUser.getLoginCode() + DateUtils.getDate("yyyyMMdd"));
                    ModelAndView modelAndView = new ModelAndView();
                    return new ModelAndView("redirect:/sso/"+queryUser.getLoginCode()+"/"+token+"?url=/a/index?relogin=true");
                }else{
                    ModelAndView modelAndView = new ModelAndView();
                    modelAndView.addObject("usercode",queryUser.getUserCode());
                    modelAndView.setViewName("modules/wxrobot/unlogin");
                    return modelAndView;
                }
            }

        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("modules/wxrobot/errorLogin");
        return modelAndView;
    }

    public String getOpenId(String code){
        Map params = new HashMap();
        params.put("secret", SECRET);
        params.put("appid", APPID);
        params.put("grant_type", "authorization_code");
        params.put("code", code);
        String result = HttpGetUtil.httpRequestToString(
                "https://api.weixin.qq.com/sns/oauth2/access_token", params);

        System.out.println("请求获取openid："+result);

        JSONObject jsonObject = new JSONObject(result);
        String openid = jsonObject.get("openid").toString();

        return openid;
    }

    public static String encryptPassword(String plainPassword){
        String plain = EncodeUtils.decodeHtml(plainPassword);
        byte [] salt = Sha1Utils.genSalt(8);
        byte [] hashPassword = Sha1Utils.sha1(plain.getBytes(),salt,1024);
        return EncodeUtils.encodeHex(salt)+EncodeUtils.encodeHex(hashPassword);
    }
}
